accessid = 'LTAILRfTv7bIefN8';
accesskey = 'XvFhmsPMdlk5S3NRqxHptVW2pRhsLC';
host = 'http://hldoss.oss-cn-hangzhou.aliyuncs.com';

g_dirname = ''
g_object_name = ''
g_object_name_type = ''
now = timestamp = Date.parse(new Date()) / 1000;

var suffixName = '';
var fileArray = new Array();

//获取图片的URL
function getPhotoUrl(FileKey, SuffixName, FileName) {
    var fileObj = new Object();
    fileObj.fileUrl = host + "/" + FileKey;//Url
    fileObj.fileKey = FileKey;//阿里云上文件的名字
    fileObj.suffixName = SuffixName;//文件后缀名
    fileObj.fileName = FileName;//上传的文件的原名
    fileArray.push(fileObj);
};
function getOssFileInfo() {
    return fileArray;
};//获取文件信息
function clearOssData() {
    fileArray = [];//清空上传图片获取接口的对象数组数据(设置数组=[])
    uploader.files.length = 0;//清空文件数组(设置length=0)
};//清除数据

var policyText = {
    "expiration": "2050-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
    "conditions": [
        ["content-length-range", 0, 1048576000] // 设置上传文件的大小限制
    ]
};

var policyBase64 = Base64.encode(JSON.stringify(policyText))
message = policyBase64
var bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, {asBytes: true});
var signature = Crypto.util.bytesToBase64(bytes);

function check_object_radio() {
    g_object_name_type = "random_name";
}

function get_dirname() {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var strDate = year + "" + month + "" + day;
    // 存放阿里云的文件夹
    g_dirname = "image/" + gUserLoginResult.userId + "/" + strDate + "/"
}

function random_string(len) {
    var date = new Date();
    var hour = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();
    var millisecond = date.getMilliseconds();
    var strTime = hour + "" + minute + "" + second + "" + millisecond;
    len = len || 32;
    var chars = '0123456789';
    var maxPos = chars.length;
    var pwd = strTime;
    for (i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

function calculate_object_name(filename) {
    if (g_object_name_type == 'local_name') {
        g_object_name += "${filename}"
    }
    else if (g_object_name_type == 'random_name') {
        suffix = get_suffix(filename)
        g_object_name = g_dirname + random_string(4) + suffix
    }
    return ''
}

function get_uploaded_object_name(filename) {
    if (g_object_name_type == 'local_name') {
        tmp_name = g_object_name
        tmp_name = tmp_name.replace("${filename}", filename);
        return tmp_name
    }
    else if (g_object_name_type == 'random_name') {
        return g_object_name
    }
}

function set_upload_param(up, filename, ret) {
    g_object_name = g_dirname;
    if (filename != '') {
        suffix = get_suffix(filename)
        calculate_object_name(filename)
    }
    new_multipart_params = {
        'key': g_object_name,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid,
        'success_action_status': '200', //让服务端返回200,不然，默认会返回204
        'signature': signature,
    };

    up.setOption({
        'url': host,
        'multipart_params': new_multipart_params
    });

    up.start();
}

var uploader = new plupload.Uploader({
    runtimes: 'html5,flash,silverlight,html4',
    browse_button: 'selectfiles',
    //multi_selection: false,
    container: document.getElementById('container'),
    flash_swf_url: 'lib/plupload-2.1.2/js/Moxie.swf',
    silverlight_xap_url: 'lib/plupload-2.1.2/js/Moxie.xap',
    url: 'http://oss.aliyuncs.com',

    //图片压缩
    resize: {
        crop: false,
        quality: 45,
        preserve_headers: false
    },

    init: {
        PostInit: function () {
            document.getElementById('ossfile').innerHTML = '';
            document.getElementById('postfiles').onclick = function () {
                set_upload_param(uploader, '', false);
                return false;
            };
        },

        FilesAdded: function (up, files) {
            plupload.each(files, function (file) {
                var fileType = get_suffix(file.name);
                if (judgeFileType(fileType) == false) {//判断文件类型
                    clearOssData();
                    return false;
                }
                document.getElementById('ossfile').innerHTML += "<div id='" + file.id + "'>&nbsp;&nbsp;&nbsp;" + (file.name).substr(0, 10) + "... (" + plupload.formatSize(file.size) + ") <b></b>"
                    + "<div class='col-sm-10'><div class='progress'><div class='progress-bar progress-bar-striped active' role='progressbar'  aria-valuemin='0' aria-valuemax='100' style='width: 0%'></div></div></div>";
                /*+'<div class="progress"><div class="progress-bar progress-bar-info progress-bar-striped active" style="width: 0%"></div></div> '
                 +'</div>';*/
            });
        },

        BeforeUpload: function (up, file) {
            check_object_radio();
            get_dirname();
            set_upload_param(up, file.name, true);
        },

        UploadProgress: function (up, file) {
            var d = document.getElementById(file.id);
            d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
            var prog = d.getElementsByTagName('div')[1];
            var progBar = prog.getElementsByTagName('div')[0];
            progBar.style.width = 2 * file.percent + 'px';
            progBar.setAttribute('aria-valuenow', file.percent);

        },

        FileUploaded: function (up, file, info) {
            if (info.status == 200) {
                document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '上传成功';
                /*get_uploaded_object_name(file.name)*/
                getPhotoUrl(get_uploaded_object_name(file.name), suffix, file.name);//获取文件名和url和后缀
            }
            else {
                document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response;
            }
        },

        Error: function (up, err) {
            document.getElementById('console').appendChild(document.createTextNode("\nError xml:" + err.response));
        }
    }
});
uploader.init();